var nowIndex = 0;
define(function (require, exports, module) {
    //remsta();//消除第一次登陆
    getYinSi();
    //设置屏幕常亮
    api.debug && api.setKeepScreenOn({ keepOn: true });
    //设置状态栏浅色
    api.setStatusBarStyle({style:'dark'}); //light  dark

    //沉侵设置顶部
    lanYun.top_h = lanYun.indexSetHeader('app-header');
    lanYun.fot_h = lanYun.setFooter('app-footer');

    //lanYun.fot_h = 0;
    var winH = api.winHeight;
    lanYun.headerH = lanYun.top_h;
    lanYun.frameH = winH - lanYun.headerH - lanYun.fot_h;

    lanYun.frameGroup.open({
        index:0,
        data:[
            {url:'html/main0/main0.html',bg:'#f6f6f6',Scroll:false, tan:false, y:lanYun.headerH , h:lanYun.frameH },
            {url:'html/main1/main1.html',Scroll:false, tan:false, y:lanYun.headerH - 40 , h:lanYun.frameH + 40  },
            {url:'html/main2/main2.html',Scroll:false, tan:false, y:lanYun.headerH - 40  , h:lanYun.frameH + 40 },
            {url:'html/main3/main3.html',Scroll:false, tan:false, y:0, h:0, xy:0, xh:winH-lanYun.fot_h},
            //{url:'html/main0/menu.html',Scroll:false, tan:false, y:winH-48 , h:48}
        ]
    });
    //事件执行
    listenerEvent = function (type) {
        //console.log('事件---'+type);
        switch(type){
            case "upclass":
                api.execScript({ frameName:'main1', script:'getData();'});
                break;
            case "updatecart":
                api.execScript({ frameName:'main2', script:'getData();'});
                getCartNum();
                break;
            case "uporderNum":
                api.execScript({ frameName:'main3', script:'getOrderNum();'});
                break;
            case "upuser":
                api.execScript({ frameName:'main3', script:'setData();'});
                break;
            case "toCart":
                api.closeToWin({name: 'root',animation:{subType:"from_left",duration:300}});
                setShowGroup(2);
                api.execScript({ frameName:'main2', script:'getData();'});
                getCartNum();
                break;
            case "toIndex":
                api.closeToWin({name: 'root',animation:{subType:"from_left",duration:300}});
                setShowGroup(0);
                break;
            case "toallpinpai":
                setShowGroup(1);
                break;
            case "mainRed":
                setMsgRed();
                break;
            default:
                break;
        }
    };
    //导航点击事件
    onTabbarClick = function (tis){
        var dst = tis.dataset;
        if(dst.id > 1){
            if(!lanYun.isLogin()){
                needLoginCall();
                return;
            }
        }
        $('.tab-button').removeClass('active');
        if($(tis).hasClass('active')) return;
        $(tis).addClass('active');
        if(dst.id == 0){
            $('#app-header').addClass('on');
        }else {
            $('#app-header').removeClass('on');
        }
        if(dst.id == 1 && nowIndex!=1){
            lanYun.event('upclass');
        }
        if(dst.id == 2 && nowIndex!=2){
            lanYun.event('updatecart');
        }
        if(dst.id == 3 && nowIndex!=3){
            lanYun.event('upuser');
        }
        nowIndex = dst.id;
        setFrameGroup(dst.id);
    };
    //导航切换方法
    setFrameGroup = function (index) {
        var resetY = lanYun.headerH;
        var resetH = lanYun.frameH;
        $('#header .headbar').hide().eq(index).show();
        lanYun.frameGroup.show(index);
    };
    //指定切换页面
    setShowGroup = function (index) {
        if(index == 0){
            $('#app-header').addClass('on');
        }else {
            $('#app-header').removeClass('on');
        }
        $('.tab-button').removeClass('active');
        $('.tabmenu'+index+'').addClass('active');
        setFrameGroup(index);
    };
    //退出APP提示
    exit_app = function (){
        api.addEventListener({name:'keyback'}, function(ret, err) {
            api.toast({ msg:'再按一次退出应用' });
            api.addEventListener({name:'keyback'}, function(ret, err) {
                api.closeWidget({silent:true});
            });
            setTimeout(function() { exit_app(); },1000);
        });
    };
    exit_app();

	//打开搜素
	open_search = function (tis) {
	    var dst = tis.dataset;
	    lanYun.openWin('main0/search.html', {
	        win:'none',
            frameParam : {id:dst.id},
	    });
	}

	//购物车编辑
	cartEdit = function(tis) {
		var dst = tis.dataset;
		if(dst.type == 0){
			$(tis).text("完成");
			$(tis).data("type",1);
		}else {
			$(tis).text("编辑");
			$(tis).data("type",0);
		}
		api.execScript({ frameName:'main2', script:'editClick('+ dst.type +');'});
	}

    //判断登录执行
    // if (lanYun.isLogin()) {
    //     getCartNum();
    // }

    //更新用户信息
    updateUdataback = function () {
        lanYun.event("upuser");
    }

    // 极光初始化
    ajpush = api.require('ajpush');
    Jpush_init();

    //监听极光推送点击事件
    api.addEventListener({name:'noticeclicked'}, function(ret, err) {
        //alert(JSON.stringify(ret));
        if (ret && ret.value) {
            if(api.systemType == 'ios'){
                var ajpush = ret.value;
            }else{
                var ajpush = JSON.parse(ret.value);
            }
            var extra = ajpush.extra;
            //push_result(extra);
            fnAjpushDeal(extra);
        }
    });

    //打开状态下监听极光推送消息
    ajpush.setListener(
        function(ret) {
            var typestr = ret.extra.type == 'pl' ? '评论和回复' : '新消息';
            api.notification({
                notify: {title:typestr,content:ret.content,extra:{extra:ret.extra}},
            }, function(ret, err) {
                var id = ret.id;
            });
        }
    );

    //Android平台，使用极光推送发送通知、消息等类型推送时，极光推送模块会往设备状态栏上发送通知，当通知被点击后，APICloud会将本次推送的内容通过事件监听回调
    api.addEventListener({
	    name: 'appintent'
	}, function(ret, err) {
	    if (ret && ret.appParam.ajpush) {
	        var ajpush = ret.appParam.ajpush;
	        var id = ajpush.id;
	        var title = ajpush.title;
	        var content = ajpush.content;
	        var extra = ajpush.extra;
	        //alert(JSON.stringify(ret));
	        fnAjpushDeal(extra);
	    }
	})

});


//极光推送初始化
function Jpush_init(){
    lanYun.getPermission(['notification']);
    if(api.systemType == 'android'){
        ajpush.init(function(ret) {
            if (ret && ret.status){
                Jpush_reg();
            }
        });
    }else{
        Jpush_reg();
    }
}

//极光推送注册别名
function Jpush_reg(){
    var udata = lanYun.getUdata();
    //console.log(JSON.stringify(udata));
    var alias_id = api.deviceId;
    if(udata && udata.id > 0){
    	alias_id = lanYun.jpushTag + udata.id;
    }
    //console.log(alias_id);
	ajpush.bindAliasAndTags({alias:alias_id,tags:['usertag']},function(ret,err) {
      	console.log('极光注册成功:'+alias_id);
    });
}

// 极光推送点击事件处理
function fnAjpushDeal (res){
	//alert(JSON.stringify(res));
    if(!lanYun.isLogin()){
        lanYun.openLogin();
        return;
    }
	if(res){
        if(res.type != 'sys'){
            delRed(res.id);
        }
        switch(res.type){
            case "sys":
                if(res.opentype == 'syspage'){
                    lanYun.openWin('main0/msg_show.html', {win:'win',title:'消息详情',frameParam : {id:res.id}});
                }
                if(res.opentype == 'myvol'){
                    delRed(res.id);
                    lanYun.openWin('user/quan/list.html', {win:'win',title:'我的优惠券',frameParam : {}});
                }
                break;
            case "audit":
                if(res.opentype == 'storein'){
                    lanYun.openWin('main3/ruzhu/shenhe.html', {win:'win',title:"入驻审核",border:1,frameParam : {}});
                }
                break;
            case "tixian":
                var sftype = res.beizhu.sftype;
                if(res.opentype == 'tixianshow'){
                    lanYun.openWin('main3/bank/tx_show.html', {win:'win',title:"提现结果",frameParam : {id:res.openid,type:sftype}});
                }
                break;
            case "downforced":
                var goodstype = res.beizhu.goodstype;
                var gtype = "";
                if(goodstype == 1){gtype = 'jifen';}
                if(res.opentype == 'storeshopshow'){
                    lanYun.openWin('main3/store/goods_show.html', {win:'win',frameParam : {id:res.openid,type:gtype}});
                }
                break;
            case "order":
                if(res.opentype == 'ordershow' || res.opentype == 'orderclose' || res.opentype == 'ordernopay'){
                    lanYun.openWin('ordert/ordert_show.html', {win:'win',title:"订单详情",border:'1',frameParam : {id:res.openid}});
                }
                break;
            default:
                break;
        }
	}

}

//设置单个已读
function delRed(id) {
    lanYun.get('UserMsg/setRead?id=' + id,function (ret){
        lanYun.toast(ret.msg);
    },0)
}

// 获取欢迎页数据打开隐私页面
function getYinSi(){
    lanYun.get('home/getad',function(ret) {
        //console.log(JSON.stringify(ret));
        if(ret.errcode==0){
            lanYun.adData = ret.data;
            init_yinsi();
        }
    });
}

// 消除第一次登陆方法
function remsta(){
    api.removePrefs({key: 'huanying_sta'});
    api.removePrefs({key: 'xiyi_sta'});
}

//引导页面
function init_startpage(){
    var hykey = api.getPrefs({sync: true,key: 'huanying_sta'});
    if(hykey == 1){
        return;
    }
    lanYun.openFrame('huanying.html' , lanYun.adData ,function(data) {
        api.setPrefs({key:'huanying_sta',value: 1});
    });
}

//打开消息
function openMsg(){
    if(!lanYun.isLogin()){
        lanYun.openLogin();
        return;
    }
    lanYun.openWin('main0/list_msg.html', {
        win:'win',
        title:'消息',
        menu:"全部已读",
        frameParam : {}
    });
}

// 设置红点
function setMsgRed (){
    var udata = lanYun.getUdata();
    $('#msgRed').hide();
    if(!udata) return;
    //console.log('执行了消息函数');
    if(udata.newmsg == 1){
        $('#msgRed').show();
    }else {
        $('#msgRed').hide();
    }
};

//协议
function init_yinsi(){
    var hykey = api.getPrefs({sync: true,key: 'xiyi_sta'});
    if(hykey == 1){
        return;
    }
    lanYun.getPermission(['camera','photos','location','microphone']);
    lanYun.openFrame('xieyi.html' , {win:'none',title:''} ,function(data) {
        api.setPrefs({key:'xiyi_sta',value: 1});
        init_startpage();
    });
}

//大屏广告页面
// function getGuanGao(){
//     lanYun.openFrame('adv.html' , {title:''} ,function() {});
//     lanYun.get('home/getad',function (ret){
//         if(ret.errcode == 0){
//             lanYun.openFrame('adv.html' , {title:''} ,function(data) {
//
//             });
//         }
//     })
// }

//窗口大小变化时
$(window).resize(function(){
    frameH = api.winHeight - lanYun.fot_h;
    api.setFrameGroupAttr({name:'groups',rect:{x:0,y:0,w:'auto',h:frameH}});
});

//获取购物车数量
function getCartNum(){
    lanYun.get('storesCart/getnum' ,function (ret) {
        //console.log(JSON.stringify(ret));
        if(ret.num == 0 || !ret.num){
            $('#cartNum').text('');
            return;
        }
        $('#cartNum').text('('+ ret.num + ')');
    });
}

//---------------------------------------------------------

//登录成功后回调
function loginCallback(udata) {
    console.log('---登录成功loginCallback----');
    var qiyuSdk = api.require('qiyuSdk');
    var params = {
        userId:udata.id,
        level:udata.isvip, //vip等级
        data:'[{\"key\":\"real_name\", \"value\":\"'+udata.nickname+'\"},{\"key\":\"mobile_phone\", \"value\":\"'+udata.phone+'\", \"label\":\"手机号\", \"hidden\":false},{\"index\":1, \"key\":\"sex\", \"label\":\"性别\", \"value\":\"'+udata.sex+'\"}]'
    }
    qiyuSdk.setUserInfo(params);
    Jpush_init();
    api.execScript({ frameName:'main3', script:'setData();'});
    api.execScript({ frameName:'main2', script:'getData();'});
    //api.execScript({ frameName:'main0', script:'setisnew();'});
    setMsgRed();
}

//退出登录后回调
function loginOutCallback(){
    console.log('---退出登录loginOutCallback----');
    Jpush_init();
    setMsgRed();
    //api.execScript({ frameName:'main0', script:'setisnew();'});
    api.execScript({ frameName:'main3', script:'setData();'});
}

//异步访问错误回调
function errorCallBack(ret) {
    //console.warn(JSON.stringify(ret));
    if(!lanYun.errIsOpen){
        lanYun.errIsOpen = 1;
        api.toast({ msg: ret.msg, duration: 2000 , global:true});
        setTimeout(function() { lanYun.errIsOpen = null; }, 2000);
    }
}

//需要登录回调函数
function needLoginCall(ret){
    //console.warn(lanYun.isloginOpen);
    if(!lanYun.isloginOpen){
        lanYun.isloginOpen = 1;
        if(ret){
            // lanYun.toast('登录失败');
            // setTimeout(function () {
            //     lanYun.isloginOpen = null;
            //     lanYun.openLogin();
            // }, 300);
            api.alert({title: '提示',msg: '您还未登录，请先登录。' }, function(ret, err) {
                lanYun.isloginOpen = null;
                lanYun.openLogin();
            });
        }else{
            lanYun.isloginOpen = null;
            lanYun.openLogin();
        }
    }
}

//需要打开网络
function needWifiCallBack(ret) {
    if(!lanYun.needWifiIsOpen){
        lanYun.needWifiIsOpen = 1;
        api.toast({ msg: '网络未连接，请检查你的网络！',location:'top', duration: 2000 , global:true });
        setTimeout(function(){
            lanYun.needWifiIsOpen = null;
        }, 1000);
    }
}

//需要更新app
function needUpdateCall(ret) {

    var lastUpdate = lanYun.getStorage('lastUpdate') || {time:0,wait:0};
    var time = Date.parse(new Date());
    var lastTime = parseInt(lastUpdate.time) + parseInt(lastUpdate.wait * 1000);
    if(lastTime > time ) {
        return;
    }
    if(!lanYun.updateIsOpen) {
        console.warn(JSON.stringify(ret))
        lanYun.updateIsOpen = 1;
        var dialogBox = api.require('dialogBox');
        var winw = api.winWidth*0.75;
        var bntW = (winw-40) / 2;
        var _texts = {content:ret.msg,rightBtnTitle: '立即更新'};
        var _styles = {
                bg: '#fff',w: winw, corner: 10,tapClose:true,
                title: {marginT: 15,titleSize: 16,titleColor:'#000'},
                content: {marginT:10,marginB: 25,color: '#888',size: 14}
            };
        if(ret.lock==1) {
            _texts.title = '版本更新';
            _styles.right = {marginB:15,marginL:15,w:winw-30, h: 35,corner:4,bg: '#F60',color:'#fff',size: 12};
        }else{
            _texts.title = '更新提示';
            _texts.leftBtnTitle = '下次再说';
            _styles.right = {marginB:15,marginL:10,w:bntW, h: 35,corner:4,bg:'#F2F2F2',color:'#090',size: 12};
            _styles.left = {marginB:15,marginL:15,w:bntW, h: 35,corner:4,bg: '#F2F2F2',color:'#444',size: 12};
        }
        dialogBox.alert({texts: _texts,styles:_styles }, function(click, err) {
            //console.warn(JSON.stringify(ret));
            lanYun.updateIsOpen = null;
            lanYun.setStorage('lastUpdate',{ time:Date.parse(new Date()), wait:ret.wait });
            dialogBox.close({dialogName: 'alert'});
            if(click.eventType == 'right') {
                lanYun.updateIsOpen = null;
                if(api.systemType == 'ios'){
                    api.openApp({
                        iosUrl: ret.iosurl,appParam: {appParam: 'lyappUpdate'}
                    });
                }else{
                    lanYun.openWin('updatepage', {win:'win_update',title:'版本更新',frameParam:ret});
                }
            }
        });
    }
}
